package com.supermarket.controller;

import com.supermarket.entity.Provider;
import com.supermarket.service.ProviderService;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/provider")
public class ProviderController {
    @Autowired
    private ProviderService providerService;
    
    @GetMapping("/{id}")
    public Provider getProvider(@PathVariable Long id) {
        return providerService.getById(id);
    }

    @GetMapping("/all")
    public List<Provider> getAll() {
        return providerService.getAll();
    }
    
    @GetMapping("/list")
    public R<Object> list(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String proCode,
            @RequestParam(required = false) String proName) {
        return providerService.getProviderList(currentPage, pageSize, proCode, proName);
    }

    @PostMapping("/create")
    public R<Void> createProvider(@RequestBody Provider provider) {
        providerService.create(provider);
        return R.createSuccess();
    }

    @PutMapping
    public R<Void> updateProvider(@RequestBody Provider provider) {
        providerService.update(provider);
        return R.createSuccess();
    }

    @DeleteMapping("/{id}")
    public R<Void> deleteProvider(@PathVariable Long id) {
        try {
            providerService.delete(id);
            return R.createSuccess();
        } catch (Exception e) {
            return R.createError(StatusCode.ERROR, "删除供应商失败，该供应商可能已有关联账单");
        }
    }
}
